import sqlite3

from GlobalData import currentUser


class SQLConn:
    def __init__(self):
        self.sqlite = sqlite3.connect('data/chatlog_%s.db' % currentUser)
        self.cur = self.sqlite.cursor()
        self.cur.execute('CREATE TABLE IF NOT EXISTS data('
                         '  Type varchar(10), '
                         '  Username varchar(20), '
                         '  Peername varchar(20), '
                         '  Body varchar(200), '
                         '  Datetime varchar(20))')

    def insertChat(self, mtype, sender, receiver, body, datetime):
        self.cur.execute(
            "INSERT INTO data VALUES ('%s', '%s', '%s', '%s', '%s')" % (mtype, sender, receiver, body, datetime))
        self.sqlite.commit()

    def loadChats(self, peer):
        self.cur.execute("SELECT * FROM data WHERE "
                         "(Username='%s' AND Peername='%s') OR "
                         "(Username='%s' AND Peername='%s')" % (currentUser, peer, peer, currentUser))
        rows = self.cur.fetchall()
        chats = []
        for row in rows:
            chats.append(row)
        return chats

    def close(self):
        self.cur.close()
        self.sqlite.close()
